import React, { useRef, useEffect } from "react";
import {
    MeshNormalMaterial, Mesh, DoubleSide,
    Matrix4, Vector3, MeshBasicMaterial,
} from 'three';
import { VertexNormalsHelper } from "three/examples/jsm/helpers/VertexNormalsHelper"
import Stage from '../component/Stage';
import BoxGeo from '../component/Mesh/BoxGeo';

const stage = new Stage();
const { scene, renderer } = stage;


const geo = new BoxGeo().getGeo();
let helper: VertexNormalsHelper;

{
    const material = new MeshNormalMaterial({
        polygonOffset: true,
        polygonOffsetFactor: 1,
        polygonOffsetUnits: 1,
        side: DoubleSide,
    });
    const box = new Mesh(geo, material);
    scene.add(box);
}
{
    const material = new MeshBasicMaterial({
        wireframe: true
    });
    const box = new Mesh(geo, material);
    helper = new VertexNormalsHelper(box, 0.5);
    scene.add(box, helper);
}

// setTimeout(function () {
//     geo.attributes.position.setY(26, 1.5);
//     geo.attributes.position.needsUpdate = true;
// }, 1000);

setTimeout(function () {
    geo.attributes.position.setY(2, 1.5);
    geo.attributes.position.needsUpdate = true;
    helper.update();//这里用的是系统计算法线, 所以自动进行了偏移
}, 1000);


let isRender: number = 0;
const CustomGeo = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(renderer.domElement);
        }
        if (isRender == 0)
            stage.animate();
        isRender++;
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default CustomGeo;